package se.vgregion.velocity.liferay.spring;

import com.liferay.portal.kernel.bean.PortletBeanLocatorUtil;
import org.springframework.web.context.support.XmlWebApplicationContext;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * @author Patrik Bergström
 */
public class VelocityBeanLocatorContextListener implements ServletContextListener {

    private static final String CONTEXT_CONFIG = "contextConfigLocation";

    private XmlWebApplicationContext ctx;

    public VelocityBeanLocatorContextListener() {
        ctx = new XmlWebApplicationContext();
    }

    public void contextInitialized(ServletContextEvent sce) {
        initializeContext(sce);
        String servletContext = sce.getServletContext().getContextPath().substring(1);
        PortletBeanLocatorUtil.setBeanLocator(servletContext, new VelocityBeanLocator());
    }

    private void initializeContext(ServletContextEvent sce) {
        ctx.setServletContext(sce.getServletContext());
        ctx.setConfigLocation(sce.getServletContext().getInitParameter(CONTEXT_CONFIG));
        ctx.refresh();
    }

    public void contextDestroyed(ServletContextEvent sce) {
        ctx.close();
    }
}
